package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author lao Chen
 * @date 2025-10-28
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(String id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> findAllProduct() {
        //从redis中查询数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //空值判断
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 新增设备
     *
     * @param deviceDto
     */
    @Transactional
    @Override
    public void insert(DeviceDto deviceDto) {
        //先判断设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //判断设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识重复");
        }
        //判断同一位置是否绑定了相同设备
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置不能绑定相同设备");
        }
        //将设备保存到数据库
        //生成设备id 生成规则为product_id + _ + node_id拼接而成
        String ioId = deviceDto.getProductKey() + "_" + deviceDto.getNodeId();
        deviceDto.setIotId(ioId);
        String secret = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        //转成数据对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        //门禁设置为0
        device.setHaveEntranceGuard(0);
        //保存到数据库
        save(device);
        //注册到IOT平台
        registerDevice(deviceDto,secret);

    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.根据产品和设备从TOT平台上查询详情
        //调用华为云接口
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        //设置设备id
        showDeviceRequest.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(showDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，同步失败");
        }

        //2.根据设备id从数据库查询详情
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //判断是否为空
        if(device == null){
            throw new BaseException("设备不存在");
        }

        //3.合并数据，返回数据
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceDetailVo.setDeviceStatus(response.getStatus());
        //时间转换，转为东八区时间
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)){
            LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            //日期和时间转换
            time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(time);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备上传信息
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        //创建一个请求对象
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        //发起请求,得到响应对象
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response.getHttpStatusCode() != 200){
            log.error("物联网接口 - 获取设备影子数据失败");
            throw new BaseException("物联网接口 - 查询设备上传信息，同步失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        //判断shadow是否为空
        if(CollUtil.isEmpty(shadow)){
            //返回空
            return Collections.emptyList();
        }
        //将shadow转换成json对象
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        //创建一个List<DeviceShadowDataVo>接收json对象的数据
        ArrayList<DeviceShadowDataVo> list = new ArrayList<>();
        //处理上报的时间
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(),"yyyyMMdd'T'HHmmss'Z'");
        //日期时间转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        jsonObject.forEach((key,value)->{
            DeviceShadowDataVo deviceShadowDataVo = new DeviceShadowDataVo();
            deviceShadowDataVo.setFunctionId(key);
            deviceShadowDataVo.setEventTime(eventTime);
            deviceShadowDataVo.setValue(value.toString());
            list.add(deviceShadowDataVo);
        });
        return list;
    }

    /**
     * 根据ioId删除设备
     *
     * @param iotId
     */
    @CacheEvict(value = "device:*")
    @Override
    public void deleteByioID(String iotId) {
        //删除数据库数据
        deviceMapper.deleteDeviceByiotId(iotId);
        //删除IOT平台数据，创建请求
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        //构造请求，设置设备id
        deleteDeviceRequest.setDeviceId(iotId);
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            log.error("物联网接口 - 删除设备失败");
            throw new RuntimeException(e);

        }

    }

    /**
     * 修改设备信息
     *
     * @param deviceDto
     */
    @Override
    public void updateDeviceInfo(DeviceDto deviceDto) {
        //修改数据库数据
        updateById(BeanUtil.toBean(deviceDto, Device.class));

        //修改IOT平台数据
        //创建一个请求对象
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        //获取iotId，给请求设置参数
        request.setDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withExtensionInfo(deviceDto.getProductKey());
        body.withDescription(deviceDto.getDeviceDescription());
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        //判断响应码
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 修改设备信息，同步失败");
        }
    }

    /**
     * 注册设备到华为云平台上
     * @param deviceDto
     */
    private void registerDevice(DeviceDto deviceDto,String secret) {
        //创建一个请求对象
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        //添加设备的本身信息，封装请求体
        AddDevice addDevice = new AddDevice();
        addDevice.withProductId(deviceDto.getProductKey());
        addDevice.withDeviceName(deviceDto.getDeviceName());
        addDevice.withNodeId(deviceDto.getNodeId());
        //生成设备id，生成规则为product_id + _ + node_id拼接而成
        addDevice.withDeviceId(deviceDto.getIotId());
        addDeviceRequest.withBody(addDevice);
        //秘钥
        AuthInfo authInfo = new AuthInfo();
        authInfo.withSecret(secret);
        addDevice.withAuthInfo(authInfo);
        addDeviceRequest.withBody(addDevice);

        try {
            AddDeviceResponse response = client.addDevice(addDeviceRequest);
            System.out.println("response.getDeviceId = " + response.getDeviceId());
        }catch (Exception e){
            log.error("注册设备失败",e);
            throw new BaseException("注册设备失败");
        }
    }
}
